package top.aicey.ai.sparring.biz.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.aicey.ai.sparring.biz.ILoginBiz;
import top.aicey.ai.sparring.common.constants.AIErrorConstants;
import top.aicey.ai.sparring.common.constants.EntityConstants;
import top.aicey.ai.sparring.common.utils.UUIDUtils;
import top.aicey.ai.sparring.dto.model.BaseResponse;
import top.aicey.ai.sparring.dto.req.LoginRequest;
import top.aicey.ai.sparring.dto.res.LoginResponse;
import top.aicey.ai.sparring.entity.system.Role;
import top.aicey.ai.sparring.entity.system.User;
import top.aicey.ai.sparring.service.IRoleService;
import top.aicey.ai.sparring.service.IUserService;

import java.time.Duration;
import java.util.Objects;

@Service
public class LoginBizImpl implements ILoginBiz {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public BaseResponse<LoginResponse> login(LoginRequest request) {
        User user = userService.getOne(Wrappers.query(User.class)
                .eq(EntityConstants.ACCOUNT, request.getAccount())
                .eq(EntityConstants.PASSWORD, request.getPassword())
        );

        if (Objects.isNull(user)){
            return BaseResponse.getFailedResponse(AIErrorConstants.LOGIN_FAIL);
        }

        Role role = roleService.getById(user.getId());

        String accessToken = UUIDUtils.get32UUID();
        RBucket<LoginResponse> bucket = redissonClient.getBucket(String.format("access_token:%s", accessToken));

        LoginResponse response = new LoginResponse();
        response.setAccount(user.getAccount());
        response.setUsername(user.getUsername());
        response.setRoleId(role.getId());
        response.setRoleName(role.getName());
        bucket.set(response,Duration.parse("PT24H"));
        response.setAccessToken(accessToken);
        return BaseResponse.getSuccessResponse(response);
    }
}
